package de.projectgoodmorning.alarm;

import java.util.Calendar;

import android.content.Context;
import android.content.Intent;
import android.test.ServiceTestCase;
import de.projectgoodmorning.alarm.model.generic.Alarm;
import de.projectgoodmorning.alarm.model.generic.AlarmCallback;

public class AlarmControllerTest extends ServiceTestCase<AlarmController> {

	public AlarmControllerTest( Class<AlarmController> serviceClass ) {
		super( serviceClass );
	}

	private AlarmController alarmController;
	private boolean isExecuted = false;
	
	protected void setUp() throws Exception {
		Context ctx = getContext();
		startService( new Intent( ctx, AlarmController.class ) );
		bindService( new Intent( ctx, AlarmController.class ) );
	}

	public void test_it_should_ignore_add_alarm_in_past() {
		Calendar cal = Calendar.getInstance();
		cal.add( Calendar.MINUTE, -10 );
		
		Alarm alarm = new Alarm( cal.getTimeInMillis(), null );
		alarm.id = 1001;
		
		alarmController.addAlarm( alarm );
		Alarm a = alarmController.getById( 1001 );
		assertTrue( a == null );
	}

	public void test_it_should_add_alarm_in_future() {
		Calendar cal = Calendar.getInstance();
		cal.add( Calendar.MINUTE, 10 );
		Alarm alarm = new Alarm( cal.getTimeInMillis(), null );
		alarm.id = 1001;
		
		alarmController.removeById( alarm.id );
		
		alarmController.addAlarm( alarm );
		Alarm a = alarmController.getById( 1001 );
		assertTrue( a != null );
	}
	
	public void test_it_should_remove_active_alarm() {
		alarmController.removeById( 1001 );
	
		Alarm a = alarmController.getById( 1001 );
		assertTrue( a == null );
	}
	
	public void test_it_should_execute_alarm() {
		Calendar cal = Calendar.getInstance();
		cal.add( Calendar.SECOND, 1 );
		Alarm alarm = new Alarm( cal.getTimeInMillis(), new AlarmCallback() {
			@Override
			public void callback( Object obj ) {
				isExecuted = true;
			}
		} );
		alarm.id = 1001;
		
		alarmController.addAlarm( alarm );
		while( !isExecuted );
		assertTrue( isExecuted );
	}
}
